package com.fzy.modules.bill.service;

import com.fzy.core.common.IDUtils;
import com.fzy.core.common.PageObject;
import com.fzy.modules.bill.dao.SoBillDao;
import com.fzy.modules.bill.dao.SoBillDetailDao;
import com.fzy.modules.bill.entity.SoBill;
import com.fzy.modules.bill.entity.SoBillDetail;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 销售订单详情
 */
@Service
public class SoBillDetailService  {
    @Autowired
    SoBillDetailDao soBillDetailDao;
    @Autowired
    SoBillDao soBillDao;
    public Integer  isWithSoBillDetail(String id){
        return soBillDetailDao.isWithSoBillDetail(id);
    }
    /**
     * 查询某个销售单号的详情
     */
    public PageObject<SoBillDetail> findBySoBillId(SoBillDetail soBillDetail, int page, int rows){
        PageHelper.startPage(page, rows);
        List<SoBillDetail> sobills = soBillDetailDao.findBySoBillId(soBillDetail);
        //查询之后获取分页对象
        PageInfo<SoBillDetail> pageInfo=new PageInfo<SoBillDetail>(sobills);
        //构建我们自定义的分页实体返回类
        PageObject<SoBillDetail> pageObject=new PageObject<SoBillDetail>();
        pageObject.setTotal(pageInfo.getTotal());
        pageObject.setRows(sobills);
        return pageObject;
    }
    /**
     * 添加销售详情，同事要更改销售订单的销售金额
     * @throws Exception 
     */
    
    public Integer saveSoBill(SoBillDetail soBillDetail) throws Exception{
        
			Double goodsMoney=soBillDetail.getGoodsMoney();
			Double tax=soBillDetail.getTax();
			Double moneyWithTax=soBillDetail.getMoneyWithTax();
			SoBill soBill=new SoBill();
			soBill.setId(soBillDetail.getSoBillId());
			SoBill sb=soBillDao.findAllSoBills(soBill).get(0);
			if(sb.getGoodsMoney()!=null){
			    soBill.setGoodsMoney(goodsMoney+sb.getGoodsMoney());
			}else{
			    soBill.setGoodsMoney(goodsMoney);
			}
			if(sb.getTax()!=null){
			    soBill.setTax(tax+sb.getTax());
			}else{
			    soBill.setTax(tax);
			}
			if(sb.getMoneyWithTax()!=null){
			    soBill.setMoneyWithTax(moneyWithTax+sb.getMoneyWithTax());
			}else{
			    soBill.setMoneyWithTax(moneyWithTax);
			}
			soBillDao.checkOut(soBill);
			soBillDetail.setId(IDUtils.genItemId());
			soBillDetail.setDateCreated(new Date());
			if(StringUtils.isEmpty(soBillDetail.getCompanyId())){
			    soBill.setCompanyId("4D74E1E4-A129-11E4-9B6A-782BCBD7746B");
			}
			if(StringUtils.isEmpty(soBillDetail.getDataOrg())){
			    soBill.setDataOrg("01010001");
			}
			soBillDetail.setWsCount(0);
			soBillDetail.setLeftCount(soBillDetail.getGoodsCount());
			return soBillDetailDao.insert(soBillDetail);
    }
}
